package com.tuoren.forward.config;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

	@Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory();
        /**连接超时*/
        factory.setConnectTimeout(15000);
        /**读超时*/
        factory.setReadTimeout(5000);
        return factory;
    }
	
	/**
     * 初始化请求模板
     * @param
     * @return
     */
    @Bean("restTemplate")
    public RestTemplate restTemplate(){

        RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(simpleClientHttpRequestFactory()));
        /**解决中文乱码问题*/
        List<HttpMessageConverter<?>> messageConverterList =  restTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverterList.iterator();
        while ( iterator.hasNext()){
            HttpMessageConverter<?> converter = iterator.next();
            // 原有的String是ISO-8859-1编码 ，设置为UTF-8
            if (converter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
                break;
            }
        }
        return restTemplate;
    }

}
